package com.xtaller.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xtaller.core.format.J;
import com.xtaller.core.format.M;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by Taller on 2017/8/7.
 */
@Component
public class TokenFilter extends ZuulFilter {
    private static Logger log = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        try {
            HttpServletRequest request = ctx.getRequest();
            String url = request.getRequestURL().toString();
            Object accessToken = request.getParameter("token");
            //公共路由不需要认证
            if (url.indexOf("/public/") == -1) {
                if (accessToken == null) {
                    ctx.setSendZuulResponse(false);
                    ctx.setResponseStatusCode(401);
                    try {
                        ctx.getResponse().getWriter().write(J.o2s(M.data("token is empty")));
                    } catch (Exception e) {
                    }
                    //校验token有效性

                    return null;
                }
            }
            return null;
        }catch (Exception ex){
            log.debug("AAAAAAAAAAAAAAAAAA");
            return null;
        }
    }

}
